using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

public class MainMenu : MonoBehaviour
{



    public float fadeSpeed = 1.5f;      // ?????????
    public float alpha;
    public Image image;
    public RenderTexture[] renders;
    public int lastIndex;

    public static VideoPlayer vp;
    public GameObject videoPlayer;
    public static RawImage ri;
    public static bool isUsingOne = true;



    private void Awake()
    {
        videoPlayer = GameObject.Find("VideoPlayer");
        image = GameObject.Find("FadeOut").GetComponent<Image>();
        vp = videoPlayer.GetComponent<VideoPlayer>();
        ri = videoPlayer.GetComponent<RawImage>();
        //vp.renderMode = VideoRenderMode.RenderTexture;
    }

    private void Start()
    {
        ri.texture = renders[int.Parse(Settings.setting.opa[2])];
        vp.targetTexture = renders[int.Parse(Settings.setting.opa[2])];
        lastIndex = int.Parse(Settings.setting.opa[2]);
        //vp.Play();

    }

    void OnEnable()
    {
        
        if(lastIndex!= int.Parse(Settings.setting.opa[2])){
            lastIndex = int.Parse(Settings.setting.opa[2]);
            ri.texture = renders[int.Parse(Settings.setting.opa[2])];
            vp.targetTexture = renders[int.Parse(Settings.setting.opa[2])];
            vp.targetTexture.Release();
            vp.frame = 1;
        }
        vp.Play();
        StartCoroutine(FadeIn());
    }

    private void OnDisable()
    {
        vp.Stop();
    }



    IEnumerator FadeIn()
    {
        alpha = 1;

        while(alpha > 0f)
        {
            alpha -= fadeSpeed;
            image.color = new Color(0,0,0,alpha);
            yield return null;
        }

    }

    IEnumerator FadeOut(string SceneName)
    {
        alpha = 0;
        while(alpha < 1)
        {
            alpha += fadeSpeed;
            image.color = new Color(0, 0, 0, alpha);
            yield return null;

        }
        SceneManager.LoadScene(SceneName);
    }

    public void StartGameButtonClicked()
    {
        //????????????????????????

        StartCoroutine(FadeOut("Level_0"));

    }



    public void QuitGameButtonClicked()
    {
        //??????,??????????
        string path = "Set.txt";
        string settingInfo = JsonUtility.ToJson(Settings.setting);
        StreamWriter sw = new StreamWriter(path);
        sw.WriteLine(settingInfo);
        sw.Close();
        //UnityEditor.EditorApplication.isPlaying = false;
        Application.Quit();
    }
}
